package com.example.family_sec.service;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;


import com.alibaba.fastjson.JSON;
import com.example.family_sec.LogUtil;
import com.example.family_sec.MyReceiver;
import com.example.family_sec.NotificationUtil;
import com.example.family_sec.models.SecInfo;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

// 发送和接受信息的service
public class MessageService extends Service {
    private static final String TAG = MessageService.class.getSimpleName();
    //String.format(HostUtil.URL)
    private String WS_URL = HostUtil.URL_WS_CHAT;  //
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(WS_URL).addHeader("whoareu","family").build();
    WebSocket webSocket_send_msg;
    WSBinder wsBinder = new WSBinder();
    WsLsImpl wsLs = new WsLsImpl(wsBinder);

    boolean isBind = false;


    public void setBind(boolean bind) {
        isBind = bind;
        //String.format(HostUtil.URL_WS_CHAT,)
    }

    // web socket 重连
    private void reconnect() {
        LogUtil.i(TAG, TAG + " , reconnect");
        System.out.println("ws 重新连接...");
        okHttpClient.newWebSocket(request, wsLs);
    }

    public MessageService() {
        LogUtil.i(TAG, " constructor MSGService");
        okHttpClient.newWebSocket(request, wsLs);


    }


    @Override
    public void onCreate() {
        super.onCreate();

        LogUtil.i(TAG, " onCreate onCreate ");
        //okHttpClient.newWebSocket(request,new WsLsImpl(wsBinder));
        // 使用原来的替换
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.i(TAG, "onStartCommand");
        // return super.onStartCommand(intent, flags, startId);

        super.onStartCommand(intent, START_FLAG_REDELIVERY, startId);
        // return START_NOT_STICKY;

        // 重传 intent 启动
        return START_REDELIVER_INTENT;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtil.i(TAG, " onUnbind service");

        setBind(false);
        return true;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);

        setBind(true);

        LogUtil.i(TAG, "onRebind");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        LogUtil.i(TAG, " destroy service 销毁service  webSocket_send_msg = " + webSocket_send_msg);
        setBind(false);

        if (webSocket_send_msg != null) {
            LogUtil.i(TAG, "destroy cancel socket");
            webSocket_send_msg.cancel();
        }

    }

    class WsLsImpl extends WebSocketListener {

        private OnProxyMessage onProxyMessage;

        public WsLsImpl(OnProxyMessage onProxyMessage) {
            LogUtil.w(TAG, "WSlsImpl ......构造");
            this.onProxyMessage = onProxyMessage;
        }

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            LogUtil.w(TAG, "onOpen ws");
            webSocket_send_msg = webSocket;
            webSocket_send_msg.send("{}"); // 测试发送空的数据包

            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(50 * 1000);
                            if (webSocket_send_msg != null) {
                                webSocket_send_msg.send("{}");

                            } else {
                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);


            LogUtil.w(TAG, "onMessage current thread " + Thread.currentThread().getId() + " , name " + Thread.currentThread().getName() + " , websocket " + webSocket + " , websocket_send_msg  " + webSocket_send_msg);
            if (isBind) {
                onProxyMessage.getMessage(text);
            } else {
                LogUtil.i(TAG, WsLsImpl.class.getName() + " , onMessage but not bind ..... eun ");

                SharedPreferences sp = getApplicationContext().getSharedPreferences("settings", MODE_PRIVATE);

                boolean notification = sp.getBoolean("notification", false);
                if (! notification){
                    LogUtil.d(TAG,"get message but not notification");
                    return ;
                }
                ProxyMessage proxyMessage = JSON.parseObject(text, ProxyMessage.class);

                if (proxyMessage == null) {
                    return;
                }

                String msg = proxyMessage.getMsg();
                SecInfo secInfo = JSON.parseObject(msg, SecInfo.class);
                if (secInfo == null) {
                    return;
                }

                if (secInfo .getIllegal() == 1 && secInfo .getGas() == 1){
                    NotificationUtil.showChannel1Notification(getApplicationContext(),"疑似可疑人员非法进入并且气体异常","警告");

                } else if( 1 == secInfo.getIllegal()){
                    NotificationUtil.showChannel1Notification(getApplicationContext(),"疑似可疑人员非法进入","警告");

                } else if (1 == secInfo.getGas()){
                    NotificationUtil.showChannel1Notification(getApplicationContext(),"气体异常","警告");

                }


              //  NotificationUtil.createShowNotification("error","title",getApplicationContext());
            }
            // todo save data into database
            // ... new Thread to save data


        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            // 发送冲洗你
            sendBroadcast(new Intent(getApplicationContext(),MyReceiver.class));
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);

            LogUtil.i(TAG, "web socket closed code = " + code + " ,reason = " + reason);

            sendBroadcast(new Intent(getApplicationContext(),MyReceiver.class));
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);

            LogUtil.e(TAG, "onFailure " + webSocket + " , webSocket_send_msg " + webSocket_send_msg + " , t " + t.getMessage());
            if(t.getMessage() .contains("closed")){
                LogUtil.d(TAG,"发送断开连接的广播");
                sendBroadcast(new Intent(getApplicationContext(),MyReceiver.class));
            }

            webSocket.cancel();

            if (webSocket_send_msg != null) {
                webSocket_send_msg.close(4000, "ws failure");
                webSocket_send_msg.cancel();

                // webSocket_send_msg = null;
            }

            // 重新连接
            //reconnect();
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");

        LogUtil.i(TAG, "onBind");
        setBind(true);
        return wsBinder;
    }

    public class WSBinder extends Binder implements OnProxyMessage {

        //  private static WSBinder sWsbinder = new WSBinder();

        // 设置设置绑定 真正发送消息的 操作
        public void setOnMessageListener(Activity activity) {

            LogUtil.i(TAG, " setOnMessageListener");
            try {
                this.onMessageListener = (OnMessageListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity + " must implements " + OnMessageListener.class.getSimpleName());
            }
        }

        private OnMessageListener onMessageListener;

        public WSBinder() {
            LogUtil.w(TAG, "WSBinder constructor");
        }

        @Override
        public boolean isBinderAlive() {
            return super.isBinderAlive();
        }


        // 发送消息
        public boolean sendText(String text) {
            if (webSocket_send_msg == null) {

                return false;
            }
            return webSocket_send_msg.send(text);

        }


        public void reConnect() {

            reconnect();
        }

        @Override
        public void getMessage(String text) {

            LogUtil.w(TAG, "getMessage " + text);
            // 接口调用.......
            if (this.onMessageListener != null) {
                this.onMessageListener.onMessage(text);
            } else {
                LogUtil.i(TAG, "get message but not bind ");
            }
        }


    }

    // 当消息 web socket 到来时的接口
    // 代理消息接口
    public interface OnProxyMessage {
        void getMessage(String text);
    }

    // 在activity 类中实现这个接口, 在这个接口中操作数据
    public interface OnMessageListener {
        void onMessage(String text);
    }
}
